import 'package:flutter/material.dart';
import 'package:underline_indicator/underline_indicator.dart';
import '../navigator/hi_navigator.dart';
import '../http/core/hi_error.dart';
import '../model/home_mo.dart';
import '../http/dao/home_dao.dart';
import '../util/color.dart';
import '../util/view_util.dart';
import '../page/home_tab_page.dart';
import '../core/hi_state.dart';
import '../widget/loading_container.dart';
import '../widget/navigation_bar.dart';
import 'video_detail_page.dart';
import 'profile_page.dart';


class HomePage extends StatefulWidget {
    final ValueChanged<int> onJumpTo;

    const  HomePage({Key key,this.onJumpTo}) : super(key: key);

    _HomePageState createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage> with AutomaticKeepAliveClientMixin,TickerProviderStateMixin,WidgetsBindingObserver {
    var listener;
    TabController _controller;
    List<CategoryMo> categoryList = [];
    List<BannerMo> bannerList = [];
    bool _isLoading = true;
    Widget _currentPage;


    @override
    void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
        _controller = TabController(length: categoryList.length, vsync: this);
        HiNavigator.getInstance().addListener(this.listener = (current,pre){
            print("current:${current.page}");
            print("pre:${pre.page}");
            //页面有没有被打开
            if(widget == current.page || current.page is HomePage) {
                print("打开了首页:onresume");
            } else if(widget == pre?.page || pre.page is HomePage) {
                print("首页 onpause");
            }
            //当页面返回到首页恢复首页的状态栏样式
            if (pre?.page is VideoDetailPage && !(current.page is ProfilePage)) {
                var statusStyle = StatusStyle.DARK_CONTENT;
                changeStatusBar(color: Colors.white, statusStyle: statusStyle);
            }
        });
        //加载数据
        loadData();
    }

    //监听应用生命周期变化
    @override
    void didChangeAppLifecycleState(AppLifecycleState state){
        super.didChangeAppLifecycleState(state);
        print(':didChangeAppLifecycleState:$state');
        switch(state){
            case AppLifecycleState.inactive :
                //处于这种状态的应用程序应该假设它们可能在任何时候暂停。
                break;
            case AppLifecycleState.resumed:
                //从后台切换前台，界面可见
                changeStatusBar();
                break;
            case AppLifecycleState.paused: // 界面不可见，后台
                break;
            case AppLifecycleState.detached: // APP结束时调用
                break;
        }
    }

    @override
    void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        HiNavigator.getInstance().removeListener(this.listener);
        _controller.dispose();
        super.dispose();
    }

    @override
    Widget build(BuildContext context) {
        super.build(context);
        return Scaffold(
            body: LoadingContainer(
                isLoading: _isLoading,
                child: Column(
                    children: [
                        NavigationBar(
                            height: 50,
                            child: _appBar(),
                            color: Colors.white,
                            statusStyle: StatusStyle.DARK_CONTENT,
                        ),
                        Container(
                            color: Colors.white,
                            child: _tabBar(),
                        ),
                        Flexible(
                            child: TabBarView(
                                controller: _controller,
                                children: categoryList.map((tab) {
                                    return HomeTabPage(
                                        categoryName: tab.name,
                                        bannerList: tab.name == '推荐' ? bannerList : null);
                                }).toList()
                            )
                        )
                    ],
                ),
            ),
        );
    }

    @override
    bool get wantKeepAlive => true;

    //自定义顶部tab
    _tabBar(){
        return TabBar(
            controller: _controller,
            isScrollable: true,
            labelColor: Colors.black,
            indicator: UnderlineIndicator(
                strokeCap: StrokeCap.round,
                borderSide: BorderSide(color: primary,width: 3),
                insets: EdgeInsets.only(left: 15,right: 15)
            ),
            tabs: categoryList.map<Tab>((tab) {
                return Tab(
                    child: Padding(
                        padding: EdgeInsets.only(left: 5, right: 5),
                        child: Text(
                            tab.name,
                            style: TextStyle(fontSize: 16),
                        ),
                    ));
            }).toList()
        );
    }

    void loadData() async {
        try {
            HomeMo result = await HomeDao.get("推荐");
            if(result.categoryList != null){
                _controller = TabController(length: result.categoryList.length, vsync: this);
            }
            setState(() {
                categoryList = result.categoryList;
                bannerList = result.bannerList;
                _isLoading = false;
            });
        } on NeedAuth catch (e) {
            print(e);
            //showWarnToast(e.message);
            setState(() {
                _isLoading = false;
            });
        } on HiNetError catch (e) {
            print(e);
            //showWarnToast(e.message);
            setState(() {
                _isLoading = false;
            });
        }
    }

    _appBar(){
        return Padding(
            padding: EdgeInsets.only(left: 15,right: 15),
            child: Row(
                children: [
                    InkWell(
                        onTap: (){
                            if(widget.onJumpTo != null){
                                widget.onJumpTo(3);
                            }
                        },
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(23),
                            child: Image(
                                height: 46,
                                width: 46,
                                image: AssetImage('images/avatar.png'),
                            ),
                        ),
                    ),
                    Expanded(
                        child: Padding(
                            padding: EdgeInsets.only(left: 15,right: 15),
                            child: ClipRRect(
                                borderRadius: BorderRadius.circular(16),
                                child: Container(
                                    padding: EdgeInsets.only(left: 10),
                                    height: 32,
                                    alignment: Alignment.centerLeft,
                                    child: Icon(Icons.search,color:Colors.grey),
                                    decoration: BoxDecoration(color: Colors.grey[100]),
                                ),
                            ),
                        )
                    ),
                    Icon(
                        Icons.explore_outlined,
                        color: Colors.grey,
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 12),
                        child: Icon(
                            Icons.mail_outline,
                            color: Colors.grey,
                        ),
                    ),
                ],
            ),
        );
    }
}
